package main

import (
	"github.com/gin-gonic/gin"
	"log"
	"myself/control"
	"myself/db/managers"
	"myself/db/models"
	"myself/rsp"
	"net/http"
)

func middle() gin.HandlerFunc {
	return func(context *gin.Context) {
		accountId := control.CheckLoginState(context, context.GetHeader("token"))
		if accountId != nil {
			context.Set("account_id", *accountId)
		}
		context.Next()
	}
}

// Cors 开启跨域函数
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin") //请求头部
		if origin != "" {
			//接收客户端发送的origin （重要！）
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
			//服务器支持的所有跨域请求的方法
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
			//允许跨域设置可以返回其他子段，可以自定义字段
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			// 允许浏览器（客户端）可以解析的头部 （重要）
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
			//设置缓存时间
			c.Header("Access-Control-Max-Age", "172800")
			//允许客户端传递校验信息比如 cookie (重要)
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		//允许类型校验
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "ok!")
		}

		defer func() {
			if err := recover(); err != nil {
				log.Printf("Panic info is: %v", err)
			}
		}()
		c.Next()
	}
}
func main() {

	r := gin.Default() // 返回一个默认的gin实例
	r.Use(Cors())
	r.GET("/ping", func(c *gin.Context) {
		accountManager, err := managers.NewAccountManger()
		AccountModel, err := accountManager.GetById(1)
		if err != nil {

		}
		account := AccountModel.(*models.Account)
		rsp.SuccessResponse(c, account)
	})
	r.POST("/registered", control.Registered)
	r.POST("/login", control.Login)

	c := r.Group("/check").Use(middle())
	c.GET("/state", control.LoginEffective)

	p := r.Group("/positing").Use(middle())
	p.POST("/create", control.CreatePosting)
	p.POST("/update", control.UpdatePosting)
	p.GET("/get", control.GetAllPosting)
	p.POST("/get/condition", control.GetAllPostingByCondition)
	_ = r.Run(":8081") // 默认在 0.0.0.0:8080 上监听并服务

}
